<!DOCTYPE html>

<html>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<script type="text/javascript" src="luarpc.ws.js" charset="UTF-8"></script>

	<script type="text/javascript">
		// 打开窗口时创建 WebSocket 
		window.onload = function() {
			if(location.protocol == 'file:') {
				wsurl.value = "ws://localhost:8504/webskt"
			} else if(location.protocol == 'https:') {
				wsurl.value = "wss://" + location.hostname + ":8504/webskt"
			} else {
				wsurl.value = "ws://" + location.hostname + ":8504/webskt"
			}
			LuaRpc.openWebSocket(wsurl.value, onMessage);

			document.getElementById('wsurl').addEventListener('blur', function() {
				let value = wsurl.value;
				let options = document.getElementById('select').getElementsByTagName('option');
				for(let i = 0; i < options.length; i++) {
					if(value == options[i].value) {
						break;
					}
					if(i == options.length - 1) {
						let option = document.createElement('option');
						option.value = value;
						document.getElementById('select').appendChild(option);
					}
				}
				LuaRpc.openWebSocket(value, onMessage);
			});
		}

		// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，
		// 防止连接还没断开就关闭窗口，server端会抛异常。
		window.onbeforeunload = function() {
			LuaRpc.closeWebSocket();
		}

		// 将消息显示在网页上
		function onMessage(message) {
			log.value += message + '\r\n';
		}
	</script>

	<style>
		* {
			font-family: Consolas;
			font-size: 26px;
		}
		
		#wsurl {
			width: 920px;
		}
	</style>

	<head>
		<title>WebSocket测试</title>
	</head>

	<body>
		<input list='select' id="wsurl" rows="1" cols="64" spellcheck="false" value=""> </input>
		<datalist id="select">
			<option value="ws://localhost:8504/webskt"></option>
			<option value="wss://ehome.szwistar.com/webskt"></option>
		</datalist>
		<br>
		<br>
		<textarea id="text" rows="4" cols="64" spellcheck="false">return "hello from websocket luarpc !"</textarea>
		<br>
		<button onclick="LuaRpc.openWebSocket(wsurl.value, onMessage)">建立连接</button>
		<button onclick="LuaRpc.send(text.value)">发送消息</button>
		<button onclick="log.value = ''">消除日志</button>
		<button onclick="LuaRpc.closeWebSocket()">关闭连接</button>
		<br>
		<textarea id="log" rows="60" cols="64" readonly="readonly"></textarea>
	</body>

</html>